package com.longcai.controller.property;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.advice.RollBackExecption;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.constants.BaseConstants;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.customer.ClyjUserProperty;
import com.longcai.entity.nearby.ClyjNearbyShops;
import com.longcai.entity.order.ClyjGoodsOrderInfo;
import com.longcai.entity.property.ClyjStatement;
import com.longcai.entity.property.ClyjUserPropertyRecord;
import com.longcai.feign.client.OrderFeignClient;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.ClyjNearbyShopsService;
import com.longcai.service.property.ClyjUserPropertyRecordService;
import com.longcai.service.property.ClyjUserPropertyService;
import com.longcai.util.LoginUser;
import com.longcai.util.StringUtils;
import com.longcai.util.TokenUtils;
import com.longcai.util.UserUtil;
import com.longcai.util.excel.ExcelUtil;
import com.longcai.vo.ClyjGoodsOrderDetailsVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.solr.client.solrj.request.DelegationTokenRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户资产表 前端控制器
 * </p>
 *
 * @author M
 * @since 2019-03-21
 */
@Controller
@RequestMapping("/clyjShopProperty")
public class ClyjShopPropertyController {

    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private ClyjNearbyShopsService clyjNearbyShopsService;
    @Autowired
    private ClyjUserPropertyRecordService clyjUserPropertyRecordService;
    @Autowired
    private TokenUtils tokenUtils;

    /**
     *  资产管理 查询订单收益明细
     * @param clyjGoodsOrderInfo
     * @param pageHelper
     * @return
     */
    @GetMapping(value = "selectOrderPropertyList")
    @ResponseBody
    public PageTableResponse selectOrderPropertyList(ClyjGoodsOrderInfo clyjGoodsOrderInfo, PageHelper pageHelper) {
        String userId = UserUtil.getLoginUser().getUserId();
        QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mich_id", "clyj_uAcuMY55");
        ClyjNearbyShops cns = clyjNearbyShopsService.selectOne(queryWrapper);
        String shopsId = cns.getShopsId();
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(clyjGoodsOrderInfo).toString());
        jsonObject.put("shopsId", shopsId);
        Map<String,Object> map = new HashMap<>();
        map.put("params",jsonObject);
        map.put("pageHelper",pageHelper);

        return this.orderFeignClient.selectOrderList(map);
    }

    /**
     *  资产管理 对账单
     * @param type 1：日账单 2：月账单
     * @param pageHelper
     * @return
     */
    @GetMapping(value = "selectShopPropertyStatements")
    @ResponseBody
    public PageTableResponse selectShopPropertyStatements(String type, PageHelper pageHelper) {
        //未传递类型返回空列表
        if(type == null || type.equals("")){
            return new PageTableResponse(0,0,null);
        }
        //查询当前登录用户
        String userId = UserUtil.getLoginUser().getUserId();
        return this.clyjUserPropertyRecordService.selectShopPropertyStatements(userId,type,pageHelper);
    }

    /**
     * 资产管理 提现记录
     * @param clyjUserPropertyRecord
     * @param pageHelper
     * @return
     */
    @GetMapping(value = "selectWithdrawalRecord")
    @ResponseBody
    public PageTableResponse selectWithdrawalRecord(ClyjUserPropertyRecord clyjUserPropertyRecord, PageHelper pageHelper) {
        String userId = UserUtil.getLoginUser().getUserId();
        clyjUserPropertyRecord.setUserId(userId);
        return this.clyjUserPropertyRecordService.getUserPropertyRecords(clyjUserPropertyRecord,pageHelper);
    }

    /**
     *  导出日/月账单
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/createStatementsExcel")
    @ResponseBody
    public ApiResult createStatementsExcel(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //查询要显示List
        String type = request.getParameter("type");
        String userId = request.getParameter("userId");
        PageHelper pageHelper = new PageHelper();
        PageTableResponse pageTableResponse = this.clyjUserPropertyRecordService.selectShopPropertyStatements(userId,type,pageHelper);
        List<ClyjStatement> list = (List<ClyjStatement>) pageTableResponse.getData();

        //excel标题
        String[] title = {"时间","收入","支出","账户余额"};
        //excel文件名
        String fileName = (type.equals("1")?"日账单详情表": "月账单详情表")+".xls";
        //sheet名
        String sheetName = (type.equals("1")?"日账单": "月账单");

        String[][] content = new String[list.size()][4];
        for (int i = 0 ; i < list.size() ; i++) {
            ClyjStatement clyjStatement = list.get(i);
            content[i] = new String[4];
            content[i][0] = String.valueOf(clyjStatement.getTime());
            content[i][1] = String.valueOf(clyjStatement.getIncome());
            content[i][2] = String.valueOf(clyjStatement.getExpend());
            content[i][3] = String.valueOf(clyjStatement.getAccout());
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            fileName = new String(fileName.getBytes(),"ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ApiResult.success();
    }

}